<template>
    <div class="register-container">
        <el-card class="register-card">
            <div class="img">
                <img src="@/assets/Register.jpg " alt=" " />
            </div>

            <h2 class="title">用户注册</h2>
            <el-form :model="registerForm" :rules="rules" label-width="80px">

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"></el-input>
                </el-form-item>

                <el-form-item label="验证码" prop="verifyCode">
                    <el-input v-model="registerForm.verifyCode" placeholder="请输入验证码">
                        <template #append>
                            <el-button
                                :style="{ backgroundColor: isSending || countdown > 0 ? '#ccc' : '#4CAF50', color: 'white' }"
                                @click="sendVerifyCode" :disabled="isSending || countdown > 0">
                                {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
                            </el-button>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-checkbox v-model="agreeTerms">
                        我已阅读并同意《用户服务协议》
                    </el-checkbox>
                </el-form-item>

                <el-row :gutter="25">
                    <el-col :span="12">
                        <el-button class="btn" type="primary" @click="onRegister" :disabled="!agreeTerms">
                            注册</el-button>
                    </el-col>
                </el-row>

                <el-form-item class="footer-links">
                    <el-col class="footer-content">
                        <span @click="goToLogin" class="link">已有账号？返回登陆</span>
                    </el-col>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
<script>
import { useRouter } from 'vue-router';
import { ref } from 'vue';
import { md5 } from 'js-md5';
import { ElMessage, ElNotification } from 'element-plus';

export default {
    name: 'RegisterPage',
    setup() {
        const registerForm = ref({
            email: '',
            verifyCode: '',
            password: '',
            phone: ''
        });
        const countdown = ref(0);
        const verificationCode = ref(0);
        const isSending = ref(false);
        const agreeTerms = ref(false);
        const userName = ref(0);
        const router = useRouter(); // 使用 useRouter 获取路由实例
        const rules = {
            email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
            ],
            verifyCode: [
                { required: true, message: '请输入验证码', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' }
            ],
            phone: [
                { required: true, message: '请输入手机', trigger: 'blur' }
            ]
        };

        const sendVerifyCode = async () => {
            if (isSending.value || countdown.value > 0 || registerForm.value.email == '') return;
            isSending.value = true;
            let url = 'http://localhost:8080/api/user/sendEmailVerificationCode?email=';
            url += registerForm.value.email;
            // 发送验证码
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain',
                    'Accept': 'application/json',
                },
                body: registerForm.value.email
            }).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            }).then(data => {
                let status = data['code'];
                if (status == 200) {
                    verificationCode.value = data['msg'];
                    console.log(data['msg']);
                }
            }).catch(error => console.error('Error:', error));

            console.log('验证码发送成功');

            countdown.value = 60; // 设置倒计时时间为60秒
            const timer = setInterval(() => {
                if (countdown.value > 0) {
                    countdown.value--;
                } else {
                    clearInterval(timer);
                    isSending.value = false; // 允许再次发送验证码
                    verificationCode.value = '';
                    console.log('倒计时结束，按钮恢复');
                }
            }, 1000); // 设置定时器每1000毫秒调用一次
        };

        const onRegister = () => {
            // 注册逻辑
            console.log('注册信息:', registerForm.value);
            userName.value = generateRandomName(7);
            console.log(userName.value);
            // 验证码错误
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if (verificationCode.value != registerForm.value.verifyCode) {
                ElMessage.error('验证码错误')
                return;
            }
            // 这里可以调用后端API进行注册
            fetch('http://localhost:8080/api/user/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({
                    username: userName.value,
                    email: registerForm.value.email,
                    password: md5(registerForm.value.password),
                    phone: registerForm.value.phone,
                    avatar: "https://qh-rjgc-bucket.oss-cn-shenzhen.aliyuncs.com/test/baseav.png"
                })
            }).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`)
                }
                return response.json();
            }).then(data => {
                if (data['code'] != 200) {
                    ElNotification({
                        title: 'Error',
                        message: data['msg'],
                        type: 'error',
                    })
                }
                else if (data['code'] == 200) {
                    ElMessage({
                        message: '注册成功，请继续登录',
                        type: 'success'
                    })
                    router.push('/login');
                }
            }).catch(error => console.error('Error: ', error));
        };
        
        const goToLogin = () => {
            console.log('Router:', router); // 打印 router 实例
            if (router) {
                router.push('/login'); // 跳转到登录页面
            } else {
                console.error("Router is undefined");
            }
        };
        const generateRandomName = (length) => {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            let result = 'SD_';
            for (let i = 0; i < length; i++) {
                const randomIndex = Math.floor(Math.random() * chars.length);
                result += chars[randomIndex];
            }
            return result;
        }
        return {
            registerForm,
            countdown,
            isSending,
            agreeTerms,
            sendVerifyCode,
            onRegister,
            rules,
            goToLogin
        };
    }
}

</script>
<style scoped>
.register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f6f4ef;
}

.register-card {
    background-color: #faecd7;
    height: auto;
    width: auto;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.btn {
    height: 120%;
    width: 220%;
    border-radius: 10px;
}

.footer-content {
    display: flex;
    /* 使用 Flexbox */
    align-items: center;
    /* 垂直居中对齐 */
}


.link {
    cursor: pointer;
    /* 鼠标悬停时显示为指针 */
    color: #409EFF;
    /* 可根据需要更改颜色 */
    margin-top: 10px;
    /* 调整这个值以控制上下间距 */

}

.img {
    display: flex;
    height: auto;
    justify-content: center;
    align-items: center;
}

.separator {
    margin: 0 10px;
    /* 为分隔符添加左右间距 */
}
</style>